<script setup name="main">
import { computed, ref } from "vue"
import { getImageList } from "@/api/imageClass"
import { updateImage, deleteImage } from "@/api/image"
import { showPrompt, toast, ChangeHeaderIndex, resetHeaderIndex } from "@/composables/util"
import UploadFile from "./UploadFile.vue"

// 接收外部传入
const props = defineProps({
  openChoose: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 1
  }
})
// 当前页码
const currentPage = ref(1)
// 总条数
const total = ref(0)
// 每页条数
const limit = 10
// 指定分类下的图片列表
const list = ref([])
// 加载动画
const loading = ref(false)
// 当前图库分类ID
const imageClassId = ref(0)
// 显示对话框
const showDialog = ref(false)
// 导出方法
const emit = defineEmits(["choose"])

// 获取图库列表
const getData = async (page = null) => {
  if (typeof page === "number") currentPage.value = page
  loading.value = true
  const res = await getImageList(imageClassId.value, currentPage.value)
  list.value = res.list.map(ope => {
    ope.checked = false
    return ope
  })
  total.value = res.totalCount
  loading.value = false
}

// 根据图片分类ID，重新加载图片列表
const loadData = id => {
  // 页码设置为第一个页
  currentPage.value = 1
  // 获取当前图库分类id
  imageClassId.value = id
  getData()
}

// 重命名
const handleEdit = item => {
  // 显示输入框
  showPrompt("重命名", item.name)
    .then(async ({ value }) => {
      // 显示加载动画
      loading.value = true
      // 调用修改接口
      await updateImage(item.id, { name: value })
      // 提示成功
      toast("修改成功")
      // 刷新数据
      getData()
      // 关闭加载动画
      loading.value = false
    })
    .catch(() => {})
}

// 删除图片
const handleDelete = id => {
  // 显示加载动画
  loading.value = true
  // 调用删除接口
  deleteImage([id])
    .then(() => {
      // 提示成功
      toast("删除成功")
      // 刷新数据
      getData()
    })
    // 成功与否都关闭加载动画
    .finally(() => (loading.value = false))
}

// 显示对话框
const openUploadFile = () => (showDialog.value = true)

// 上传成功
const handleUploadSuccess = () => {
  toast("图片上传成功！")
  showDialog.value = false
  getData(1)
}

// 计算是否选中
const checkedImage = computed(() => list.value.filter(v => v.checked))

// 选中图片
const handleChooseChange = i => {
  if (i.checked && checkedImage.value.length > props.limit) {
    i.checked = false
    return toast(`最多只能选择${props.limit}张图片`, "error")
  }
  emit("choose", checkedImage.value)
}

// 导出方法
defineExpose({ loadData, openUploadFile })
</script>

<template>
  <el-main class="image-main" v-loading="loading" style="padding: 0">
    <div class="image-main-header">
      <el-row :gutter="10" style="margin: 0" v-if="list.length > 0">
        <el-col :sm="12" :lg="6" v-for="i in list" :key="i.id">
          <el-card shadow="hover" class="image-card" :body-style="{ padding: '0px' }" :class="{ checked: i.checked }">
            <el-image :src="i.url" fit="cover" :preview-src-list="[i.url]" :initial-index="0" @click="ChangeHeaderIndex" @close="resetHeaderIndex" />
            <div class="image-title">{{ i.name }}</div>
            <div class="imangBtn">
              <div class="checkbox" v-if="openChoose">
                <el-checkbox v-model="i.checked" @change="handleChooseChange(i)" />
              </div>
              <el-tooltip effect="light" content="修改" placement="bottom">
                <el-button type="primary" size="small" text @click="handleEdit(i)">
                  <el-icon :size="12"><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-popconfirm width="220" title="确认删除该图片？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDelete(i.id)">
                <template #reference>
                  <el-button class="!m-0" type="primary" size="small" text>
                    <el-icon :size="12"><Close /></el-icon>
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div v-else class="empty">
        <el-empty description="图库列表为空，快去添加吧！" />
      </div>
    </div>
    <div class="image-main-footer">
      <el-pagination background small layout="prev, pager, next" :total="total" :current-page="currentPage" :page-size="limit" :hide-on-single-page="total < 10" @current-change="getData" />
    </div>
  </el-main>
  <el-dialog v-model="showDialog" title="上传图片" width="60%">
    <UploadFile :data="{ image_class_id: imageClassId }" @success="handleUploadSuccess" />
  </el-dialog>
</template>

<style lang="scss" scoped>
.image-main {
  position: relative;
  &-header {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 50px;
    overflow-y: auto;
    padding-top: 6px;
    .empty {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .el-col {
      margin-bottom: 10px;
    }
    .image-card {
      position: relative;
      .el-image {
        width: 100%;
        height: 150px;
      }
      .image-title {
        position: absolute;
        bottom: 38px;
        left: -1px;
        right: -1px;
        padding: 0 6px;
        height: 24px;
        line-height: 24px;
        font-size: var(--text-sm);
        color: var(--white);
        white-space: nowrap;
        background: var(--text-bg);
      }
      .imangBtn {
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        padding: 4px;
        .checkbox {
          position: absolute;
          left: 10px;
        }
      }
    }
    .checked {
      border: 1px solid var(--bg2);
    }
  }
  &-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    bottom: 0;
    height: 50px;
    left: 0;
    right: 0;
  }
}
::-webkit-scrollbar {
  width: 0;
}
@media screen and (max-width: 375px), screen and (max-width: 414px) {
  .empty {
    transform: scale(0.8);
  }
  .image-title {
    padding: 6px 4px;
  }
}
</style>
